
package de.pernpas.stadtfuehrer.managedbean;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import de.pernpas.stadtfuehrer.common.Sites;
import de.pernpas.stadtfuehrer.entity.User;
import de.pernpas.stadtfuehrer.exception.BadPasswordException;
import de.pernpas.stadtfuehrer.service.UserService;
import de.pernpas.stadtfuehrer.service.UserServiceImpl;

@ManagedBean
@SessionScoped
public class AuthMB {
	private User user;
	
	public User getUser() {
		return user;
	}
	
	@PostConstruct
	public void init(){
		user = new User();
	}

	public String login(){
		String result; 
		UserService us = new UserServiceImpl();
		try {
			user = us.getUser(user.getPseudonym(), user.getPassword());
		} catch (BadPasswordException e) {
			// TODO set FacesMessages
			return "authError";
		}
		
		if(user != null){
			result = "loggedIn";
			FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(User.class.getName(), user);
		}else{
			init();
			result = "authError";
		}
		return result;
	}

	public String logout(){
		// newly init Session Bean
		init();
		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();        
		return Sites.WELCOME + "?faces-redirect=true";
	}
	
	public void setUser(User user) {
		this.user = user;
	}
}
